package com.googlecode.openrtp.grizzly.session;

import com.google.inject.Singleton;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;
import com.googlecode.openrtp.spi.RtpSession;

/**
 *
 * @author jocke
 */
@Singleton
public class RtpSessionContext {

    private static final ConcurrentHashMap<String, RtpSession> CNAME_RTP_SESSIONS = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Long, RtpSession> SSRC_RTP_SESSIONS = new ConcurrentHashMap<>();
    private final Set<SessionContextListener> listeners;

    @Inject
    public RtpSessionContext(Set<SessionContextListener> listeners) {
        this.listeners = listeners;
        System.out.println(listeners);
    }

    public RtpSession getByCname(String key) {
        SSRC_RTP_SESSIONS.values();
        return CNAME_RTP_SESSIONS.get(key);
    }

    public RtpSession putByCname(String key, RtpSession session) {
        notifyAdded(session);
        return CNAME_RTP_SESSIONS.put(key, session);
    }

    public RtpSession getBySsrc(Long key) {
        return SSRC_RTP_SESSIONS.get(key);
    }

    public RtpSession putBySsrc(Long key, RtpSession session) {
        notifyAdded(session);
        return SSRC_RTP_SESSIONS.put(key, session);
    }

    public void remove(Long ssrc, String cname) {
        CNAME_RTP_SESSIONS.remove(cname);
        RtpSession session = SSRC_RTP_SESSIONS.remove(ssrc);
        notifyRemoved(session);
    }

    private void notifyRemoved(RtpSession session) {
        if (session != null) {
            for (SessionContextListener sessionContextListener : listeners) {
                sessionContextListener.sessionRemoved(session);
            }
        }
    }

    private void notifyAdded(RtpSession session) {
        for (SessionContextListener sessionContextListener : listeners) {
            sessionContextListener.sessionAdded(session);
        }
    }

    @Override
    public String toString() {
        return "RtpSessionContext{" + "listeners=" + listeners + '}';
    }
}
